package com.link.base.base.product.model;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.link.base.base.product.service.PcdDataService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 模板的读取类
 *
 * @author Jiaju Zhuang
 */
public class PcdDataSaveListener extends AnalysisEventListener<PcdDataExcelMo> {

    private static final Logger logger = LogManager.getLogger(PcdDataSaveListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<PcdDataExcelMo> cachedDataList = new ArrayList<>();

    private Long headId; // 表头ID

    private PcdDataService  pcdDataService;


    public PcdDataSaveListener() {

    }

    public PcdDataSaveListener(PcdDataService pcdDataService,Long headId) {
        this.pcdDataService = pcdDataService;
        this.headId = headId;
    }

    @Override
    public void invoke(PcdDataExcelMo data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            try {
                saveData();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            cachedDataList = new ArrayList<>(BATCH_COUNT); // 释放原来的
        }
    }

    /**
     * 最后一步
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        try {
            saveData();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        logger.info("所有数据解析完成！");
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        super.onException(exception, context);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() throws Exception {
        // 插入记录
        logger.info("{}条数据，开始存储数据库！", cachedDataList.size());
        pcdDataService.batchInsertExcels(cachedDataList,headId);
        logger.info("存储数据库成功！");
    }

}
